<?php
namespace backend\controllers;
use yii\web\Controller;
use yii;
use backend\models\Home;
use common\Session;
use yii\web\UploadedFile;
use yii\helpers\Url;
/**
 * Created by PhpStorm.
 * User: xuan_
 * Date: 2015/9/29
 * Time: 9:18
 */
class HomeController extends Controller
{
    public function init(){
        Session::getSession()==101 ? :$this->redirect(['/login']);
    }
    public function actionIndex(){
        $model=new Home();
        $datas=Home::find()->asArray()->all();
        $data=array();
        foreach($datas as $k=>$v){
            $data[$v['name']]=$v['value'];
        }
        if(isset($_POST['submit'])){
            if(!empty($_FILES['img1']['name'])){
                $this->saveData($this->uploadImg('img1'),'img1');
            }
            if(!empty($_FILES['img2']['name'])){
                $this->saveData($this->uploadImg('img2'),'img2');
            }
            if(!empty($_FILES['img3']['name'])){
                $this->saveData($this->uploadImg('img3'),'img3');
            }
            if(!empty($_FILES['erweima']['name'])){
                $this->saveData($this->uploadImg('erweima'),'erweima');
            }
            isset($_POST['phone'])?$this->saveData($_POST['phone'],'phone'): '';
            isset($_POST['email'])?$this->saveData($_POST['email'],'email'): '';
            isset($_POST['product'])?$this->saveData($_POST['product'],'product'): '';
            isset($_POST['about'])?$this->saveData($_POST['about'],'about'): '';
            isset($_POST['img1url'])?$this->saveData($_POST['img1url'],'img1url'): '';
            isset($_POST['img2url'])?$this->saveData($_POST['img2url'],'img2url'): '';
            isset($_POST['img3url'])?$this->saveData($_POST['img3url'],'img3url'): '';
            $this->redirect(['home/index']);
        }
        $info=array(
            'rating'=>'首页',
            'define'=>'这里展示网站配置信息以及网站的访问量。'
        );
        return $this->render('index',[
            'info'=>$info,
            'data'=>$data,
            'model'=>$model
        ]);
    }
    private function saveData($data,$name){
        $updateData=Home::find()->where(['name'=>$name])->one();
        $updateData->value=$data;
        $updateData->save();
    }
    private function uploadImg($fileName){
        $type='';
        $tmpName=$_FILES[$fileName]["tmp_name"];
        $filetype = $_FILES[$fileName]['type'];
        if($filetype == 'image/jpeg'){
            $type = '.jpg';
        }
        if ($filetype == 'image/jpg') {
            $type = '.jpg';
        }
        if ($filetype == 'image/pjpeg') {
            $type = '.jpg';
        }
        if ($filetype == 'image/png') {
            $type = '.png';
        }
        if($filetype == 'image/gif'){
            $type = '.gif';
        }
        $fileUrl=Yii::$app->basePath.'/web/uploads/poster/';
        move_uploaded_file($tmpName,$fileUrl.$fileName.$type);
        return 'uploads/poster/'.$fileName.$type;
    }
}
?>